<?php

namespace frontend\controllers;

use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\FileObj;
use common\models\Config;

/**
 * File controller
 */
class FileController extends Controller {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        if (Config::getLicense()['sensorNowCount'] == 0) {
            $rules = [];
        } else {
            $rules = [
                [
                    'actions' => [''],
                    'allow' => true,
                    'roles' => ['?'],
                ],
                [
                    'actions' => ['whitepage', 'blackpage'],
                    'allow' => true,
                    'roles' => ['@'],
                ],
                [
                    'actions' => [],
                    'allow' => true,
                    'roles' => ['admin'],
                ],
            ];
        }
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['addfile', 'whitepage', 'blackpage', 'del'],
                'rules' => $rules,
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                // 'logout' => ['post'],
                // 'test' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions() {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public $enableCsrfValidation = false;

    private function isAPI() {
        $headers = Yii::$app->request->headers;
        if (stristr($headers['accept'], 'application/json') !== false) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        } else {
            Yii::$app->response->format = \yii\web\Response::FORMAT_XML;
        }
    }

    public function actionAddfile() {
        $this->isAPI();
        if (!Yii::$app->request->isPost) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'Not post request';
            return $data;
        }
        $post = json_decode(Yii::$app->request->getRawBody(), true);
        if (empty($post['MD5'])) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'SHA error';
            return $data;
        }
//        var_dump($post);die;
        $sql = "INSERT INTO `file` (`md5`,sha256,`status`,created_at,updated_at) VALUES('" . $post['MD5'] . "','" . $post['SHA256'] . "','" . $post['status'] . "'," . time() . "," . time() . ") ON DUPLICATE KEY UPDATE `status`=" . $post['status'] . ",updated_at=" . time() . ";";
        Yii::$app->db->createCommand($sql)->query();
//        $file = FileObj::find()->where(['MD5' => $post['MD5'], 'SHA256' => $post['SHA256']])->one();
//        if (empty($file)) {
//            $file = new FileObj();
//            $file->MD5 = $post['MD5'];
//            $file->SHA256 = $post['SHA256'];
//        }
//        $file->status = $post['status'];
//        $file->save();
        $page = (int) $post['page'];
        if ($post['status'] == '3') {
            $post['status'] = [FileObj::WhiteList, FileObj::IsWhite];
        }
        return $this->page($post['status'], $page);
    }

    public function actionDel() {
        $this->isAPI();
        if (!Yii::$app->request->isPost) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'Not post request';
            return $data;
        }
        $post = json_decode(Yii::$app->request->getRawBody(), true);

        if (empty($post['id'])) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'ID error';
            return $data;
        }
        $file = FileObj::findOne($post['id']);
        $file->status = FileObj::IsBad;
        $file->save();
        $page = (int) $post['page'];
        return $this->page($post['status'], $page);
    }

    public function actionWhitepage($page = 1, $rows = 15) {
        $this->isAPI();
        if (Yii::$app->request->isPost) {
            $post = json_decode(Yii::$app->request->getRawBody(), true);
            $page = empty($post['page']) ? $page : $post['page'];
            $rows = empty($post['rows']) ? $rows : $post['rows'];
        }
        $page = (int) $page;
        $rows = (int) $rows;
        return $this->page([FileObj::WhiteList, FileObj::IsWhite], $page, $rows);
    }

    public function actionBlackpage($page = 1, $rows = 15) {
        $this->isAPI();
        if (Yii::$app->request->isPost) {
            $post = json_decode(Yii::$app->request->getRawBody(), true);
            $page = empty($post['page']) ? $page : $post['page'];
            $rows = empty($post['rows']) ? $rows : $post['rows'];
        }
        $page = (int) $page;
        $rows = (int) $rows;
        return $this->page(FileObj::BlackList, $page, $rows);
    }

    private function page($status, $page = 1, $rows = 15) {
        $query = FileObj::find()->where(['status' => $status])->orderBy(['updated_at' => SORT_DESC, 'id' => SORT_DESC]);
        $page = (int) $page;
        $page = $page < 1 ? 1 : $page;
        $rows = (int) $rows;
        $count = (int) $query->count();
        $maxPage = ceil($count / $rows);
        $page = $page > $maxPage ? $maxPage : $page;
        $sensorList = $query->offSet(($page - 1) * $rows)->limit($rows)->asArray()->all();
        $data = [
            'data' => $sensorList,
            'count' => $count,
            'maxPage' => $maxPage,
            'pageNow' => $page,
            'status' => 'success',
        ];
        return $data;
    }

}
